package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TestScorePartBean;
import com.atguigu.util.ClickHouseUtil;
import com.atguigu.util.DateFormatUtil;
import com.atguigu.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsTestScorePartCount {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // TODO 2 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */

        //TODO 3 从dwd_test_exam_paper获取数据
        String dwdTestExamPaper = "dwd_test_exam_paper";
        String groupId = "dws_test_score_part_count";
        DataStreamSource<String> dataStreamSource = env.addSource(KafkaUtil.getFlinkKafkaConsumer(dwdTestExamPaper, groupId));
        //TODO 4 过滤并转换对象(过滤空值,处理撤回流)
        SingleOutputStreamOperator<JSONObject> jsonObjStream = dataStreamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null && !"".equals(value) && !"null".equals(value)) {
                    out.collect(JSON.parseObject(value));
                }
            }
        });
        SingleOutputStreamOperator<TestScorePartBean> beanStream = jsonObjStream.keyBy(value -> value.getString("id"))
                .process(new KeyedProcessFunction<String, JSONObject, TestScorePartBean>() {
                    ValueState<JSONObject> lastJsonState = null;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<JSONObject> lastJsonDescriptor = new ValueStateDescriptor<>("lastJson", JSONObject.class);
                        lastJsonDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(org.apache.flink.api.common.time.Time.days(1L)).build());
                        lastJsonState = getRuntimeContext().getState(lastJsonDescriptor);
                    }

                    @Override
                    public void processElement(JSONObject value, Context ctx, Collector<TestScorePartBean> out) throws Exception {
                        JSONObject lastJson = lastJsonState.value();
                        if (lastJson == null) {
                            ctx.timerService().registerProcessingTimeTimer(System.currentTimeMillis() + 5000L);
                            lastJsonState.update(value);
                        } else {
                            if (lastJson.getLong("rt") < value.getLong("rt")) {
                                lastJsonState.update(value);
                            }
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<TestScorePartBean> out) throws Exception {
                        JSONObject value = lastJsonState.value();
                        Double score = value.getDouble("score");
                        Long goodCt = 0L;
                        Long passCt = 0L;
                        Long noPassCt = 0L;
                        if (score >= 0.0 && score < 60) {
                            noPassCt = 1L;
                        } else if (score >= 60 && score < 80) {
                            passCt = 1L;
                        } else if (score >= 80) {
                            goodCt = 1L;
                        }
                        out.collect(TestScorePartBean.builder()
                                .goodCt(goodCt)
                                .passCt(passCt)
                                .noPassCt(noPassCt)
                                .ts(value.getLong("ts") * 1000L)
                                .build());
                    }
                });
        //TODO 5 设置水印,开窗聚合
        SingleOutputStreamOperator<TestScorePartBean> reduceStream = beanStream.assignTimestampsAndWatermarks(WatermarkStrategy
                .<TestScorePartBean>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                .withTimestampAssigner(new SerializableTimestampAssigner<TestScorePartBean>() {
                    @Override
                    public long extractTimestamp(TestScorePartBean element, long recordTimestamp) {
                        return element.getTs();
                    }
                })
        ).windowAll(TumblingEventTimeWindows.of(Time.seconds(10L)))
                .reduce(new ReduceFunction<TestScorePartBean>() {
                            @Override
                            public TestScorePartBean reduce(TestScorePartBean value1, TestScorePartBean value2) throws Exception {
                                value1.setGoodCt(value1.getGoodCt() + value2.getGoodCt());
                                value1.setPassCt(value1.getPassCt() + value2.getPassCt());
                                value1.setNoPassCt(value1.getNoPassCt() + value2.getNoPassCt());
                                return value1;
                            }
                        },
                        new AllWindowFunction<TestScorePartBean, TestScorePartBean, TimeWindow>() {
                            @Override
                            public void apply(TimeWindow window, Iterable<TestScorePartBean> values, Collector<TestScorePartBean> out) throws Exception {
                                TestScorePartBean next = values.iterator().next();
                                next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                                next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                                next.setTs(System.currentTimeMillis());
                                out.collect(next);
                            }
                        });

        //TODO 6 写入到clickhouse
        reduceStream.addSink(ClickHouseUtil.getClickHouseSink("insert into dws_test_score_part_count_window values(?,?,?,?,?,?)"));
        //TODO 7 启动
        env.execute(groupId);

    }
}
